package com.apetrenko.avaya.callstore.server;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.apetrenko.avaya.callstore.client.Record;

public class DownloadServlet extends HttpServlet {

	private static final long serialVersionUID = -1525292320752597512L;

	@Override
	protected void doGet(HttpServletRequest aReq, HttpServletResponse aResp)
			throws ServletException, IOException {

		ServletContext vContext = getServletConfig().getServletContext();
		DbAdapter vAdapter = (DbAdapter) vContext
				.getAttribute(ContextListener.ATTR_DBADAPTER);

		if (vAdapter != null) {
			
			
			long vRecordId = Long.parseLong(aReq.getPathInfo().replaceAll("/", ""));

			Record vRecord = vAdapter.getRecord(vRecordId);

			if (vRecord != null) {
				File vFile = new File(vRecord.getRecordUrl());
				int vLength = 0;
				ServletOutputStream vOutStream = aResp.getOutputStream();

				String vMimetype = null;

				aResp.setContentType((vMimetype != null) ? vMimetype
						: "application/octet-stream");
				aResp.setContentLength((int) vFile.length());
				aResp.setHeader("Content-Disposition",
						"attachment; filename=\"" + "record.wav"
								+ "\"");

				byte[] vBuf = new byte[20480];
				DataInputStream vInStream = new DataInputStream(
						new FileInputStream(vFile));

				while ((vInStream != null)
						&& ((vLength = vInStream.read(vBuf)) != -1)) {
					vOutStream.write(vBuf, 0, vLength);
				}

				vInStream.close();
				vOutStream.flush();
				vOutStream.close();
			}

		}
	}

	@Override
	protected void doPost(HttpServletRequest aReq, HttpServletResponse aResp)
			throws ServletException, IOException {

		doGet(aReq, aResp);
	}

}
